package com.jvyou.app.ds.apo;

import com.jvyou.app.common.annotation.DictType;
import com.jvyou.app.common.domain.model.PageResult;
import com.jvyou.app.common.domain.model.Result;
import com.jvyou.app.ds.service.DictDataService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.util.List;

@Slf4j
@Aspect
@Component
@RequiredArgsConstructor
public class DictAspect {

    @Autowired
    private DictDataService dictDataService;

    //    @AfterReturning(pointcut = "execution(* com.yomsun..controller..*(..))", returning = "result")
    @AfterReturning(pointcut = "@annotation(com.jvyou.app.common.annotation.AutoDict)", returning = "result")
    public void processDict(Object result) {
        if (result == null) {
            return;
        }
        // 提取数据
        Object data = extractData(result);
        if (data == null) {
            return;
        }
        if (data instanceof List) {
            ((List<?>) data).forEach(this::convertDict);
        } else {
            convertDict(data);
        }
    }

    /**
     * 从返回值中提取数据
     */
    private Object extractData(Object result) {
        if (result instanceof Result) {
            Object data = ((Result<?>) result).getData();
            if (data instanceof PageResult) {
                return ((PageResult<?>) data).getData();
            }
            return data;
        }
        return null;
    }

    /**
     * 转换字典值
     */
    private void convertDict(Object obj) {
        if (obj == null) {
            return;
        }
        // 2. 获取对象的所有字段
        Field[] fields = obj.getClass().getDeclaredFields();
        for (Field field : fields) {
            // 检查字段是否包含 @DictType 注解
            if (field.isAnnotationPresent(DictType.class)) {
                DictType dict = field.getAnnotation(DictType.class);
                field.setAccessible(true);
                try {
                    // 获取字段的值
                    Object value = field.get(obj);
                    if (value != null) {
                        // 获取字典标签
                        String dictLabel = dictDataService.getLabel(dict.value(), value.toString());
                        // 动态添加字典标签字段
                        String labelFieldName = field.getName() + "Label";
                        Field labelField = obj.getClass().getDeclaredField(labelFieldName);
                        labelField.setAccessible(true);
                        labelField.set(obj, dictLabel);
                    }
                } catch (IllegalAccessException | NoSuchFieldException e) {
                    log.error("字典转换失败", e);
                }
            }
        }
    }
}
